<?php

class ArticleDetail extends AbstractBox {
	protected $template = 'article/detail.tpl';
	
	/**
	 * @var	tslib_pibase
	 */
	protected $cObject = NULL;
	
	public function __construct($cObject) {
		$this->cObject = $cObject;
	}
	
	protected function setup() {
		if (Utils::post('diskusia')) {
			$data = Utils::post();
			$validation = $this->validateDiscussionForm($data);
			if ($validation !== TRUE) {
				MySmarty::assign('errors', $validation);
			} else {
				$data = $this->prepareDataToSave($data);
				$post = new Post($data);
				$post->save();
				//MySmarty::assign('message', 'Váš príspevok bol pridaný do diskusie');
				Utils::redirect(Utils::getActualUrlWithoutGetParameters() . '#diskusia', FALSE);
			}
		}
		
		$articleRepository = new ArticleRepository();
		$article = $articleRepository->getOneByAlias($_GET['alias']);
		if ($article) {
			$article['bodytext'] = $this->cObject->pi_RTEcssText($article['bodytext']);
			MySmarty::assign('article', $article);
		} else {
			// TODO 404
		}
	}
	
	protected function validateDiscussionForm($data) {
		$errors = array();
//		if (trim($data['title']) == '') {
//			$errors['title'] = 'Vyplňte nadpis';
//		}
//		
		if (trim($data['bodytext']) == '') {
			$errors['bodytext'] = 'Vyplňte odpoveď';
		}
		
		if (!$data['fk_user_id']) {
			$errors['user'] = 'Musíte byť prihlásený';
		}
		
		if ($errors) {
			return $errors;
		}
		return TRUE;
	}
	
	protected function prepareDataToSave($data) {
		unset($data['diskusia']);
		
		$data['pid'] = 56;	// TOTO by malo byt v configu ale zadara sa mi to nechce robit :)
		$data['crdate'] = time();
		$data['tstamp'] = time();
		
		return $data;
	}
}

?>